#!/usr/bin/python -t
import commands
import sys
import string
import re

if len(sys.argv)<2:
	print "ERRORE PARAMETRI"
	sys.exit(3)  #UNKNOWN


def statuscode(checkval):
	if re.match(r'^.* OK',checkval,re.IGNORECASE):
		return 0
	elif re.match(r'^.* WARNING',checkval,re.IGNORECASE):
		return 1
	elif re.match(r'^.* CRITICAL',checkval,re.IGNORECASE):
		return 2
	else:	
		return 3
	


BASECOMMAND="/usr/lib/nagios/plugins/check_nrpe -H " 
ARG=sys.argv[2:]
ENABLENRPE=str(sys.argv[1])
if  ENABLENRPE  == "1" :
	HOSTADDRESS=ARG[0]
	HOSTGW=ARG[1]
#	print "HOST "+HOSTADDRESS
#	print "GW "+HOSTGW
	finalcmd=str(ARG[3:]).replace(',','').replace('\'','').replace('[','').replace(']','')
#	print "FINALCMD "+finalcmd
	if len(finalcmd)!="0":
		finalcmd=" -a "+finalcmd
	nrpe_cmd=HOSTADDRESS+" -c "+ARG[2]+"  "+finalcmd
	#nrpe_cmd=HOSTADDRESS+" -c "+ARG[2]+" -a "+finalcmd
	strcom=BASECOMMAND+" "+HOSTGW+" -c check_nrpe -a  \' -H "+nrpe_cmd+"\'"
#	print "nrpe_cmd "+nrpe_cmd
	comdc=commands.getstatusoutput(strcom)
#	returncmd = comdc[1].split(' ')
	returncmd=str(comdc).replace(',','').replace('\'','').replace('(','').replace(')','')
	print returncmd
	#print returncmd+"--"+strcom # DECOMMENTARE PER DEBUG
	scode=statuscode(returncmd) #RITORNA IL CODICE DI ERRORE COME INT
	sys.exit(int(scode))

else:
	HOSTGW=sys.argv[2] 	 # GW DI PASSAGGIO
	HOSTADDRESS=sys.argv[3]	 # IP DA CONTROLLARE
	finalcmd=str(ARG[2:]).replace(',','').replace('\'','').replace('[','').replace(']','')
#	print len(finalcmd)
	if len(finalcmd)!="0":
		finalcmd=" -a "+finalcmd
	nrpe_cmd=" -c "+ARG[1]+" "+finalcmd
	#nrpe_cmd=" -c "+ARG[1]+" -a "+finalcmd
	strcom=BASECOMMAND+" "+HOSTGW+" "+nrpe_cmd	
#	print strcom # COMPARE NEL MESSAGGIO DI CHECK
##	comdc=commands.getstatusoutput('/usr/lib/nagios/plugins/check_nrpe -H 10.0.1.34 -c check_dummy -a 1 DIRETTO--'+strcom)
	comdc=list(commands.getstatusoutput(strcom)) 
	returncmd=str(comdc).replace(',','').replace('\'','').replace('(','').replace(')','')
	print returncmd
	scode=statuscode(returncmd) #RITORNA IL CODICE DI ERRORE COME INT
	sys.exit(int(scode))
	#lsa=comdc[1].split(' ')
	#retval=lsa[0]	
	#descr=' '.join(lsa[1:])
	#scode=statuscode(str(retval)) #RITORNA IL CODICE DI ERRORE COME INT
	#print retval+" "+descr
	##print retval+" "+descr+"--"+strcom # DECOMMENTARE PER DEBUG
	#sys.exit(int(scode))
	

#check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -a $ARG2$ $ARG3$ $ARG4$ $ARG5$ $ARG6$ 
#check_nrpe -H $HOSTGW$ -c check_nrpe -a "-H $HOSTADDRESS$ -c check_load  -a 2,3,4 4,5,6"
